import socket
import json
import argparse
import time

def send_message(host, port, message):
    try:
        # 创建TCP socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print(f"正在连接服务器 {host}:{port}...")
        
        # 连接服务器
        sock.connect((host, port))
        print("连接成功!")
        
        # 发送消息时添加标记
        framed_message = f"\x02{message}\x03"
        print(f"发送消息: {message}")
        sock.sendall(framed_message.encode('gbk'))
        # sock.sendall(message.encode('utf-8'))
        print("消息发送完成,等待服务器响应...")
        
        # 设置接收超时时间(秒)
        sock.settimeout(600)
        
        # 用于存储未完成的消息
        buffer = ""
        
        while True:
            try:
                data = sock.recv(4096)
                if not data:
                    print("服务器关闭了连接")
                    break
                
                buffer += data.decode('gbk')
                
                # 处理所有完整的消息
                while '\x02' in buffer and '\x03' in buffer:
                    start = buffer.find('\x02')
                    end = buffer.find('\x03')
                    
                    if start < end:
                        # 提取消息内容（不包含标记符）
                        message = buffer[start+1:end]
                        # 更新缓冲区，移除已处理的消息
                        buffer = buffer[end+1:]
                        
                        try:
                            response = json.loads(message)
                            print(f"收到响应: {json.dumps(response, indent=2, ensure_ascii=False)}")
                            
                            # 处理特定类型的响应
                            if response.get("type") == "position_data":
                                if response.get("bIsLast"):
                                    print("收到最后一条持仓数据，结束监听")
                                    return
                                    
                            elif response.get("type") == "response" and response.get("action") == "orderInsert":
                                print("等待成交回报...")
                                continue
                                
                            elif response.get("type") == "trade":
                                print("收到成交回报,结束监听")
                                return
                                
                        except json.JSONDecodeError as e:
                            print(f"JSON解析错误: {e}")
                            print(f"错误数据: {message}")
                    else:
                        # 开始标记在结束标记之后，说明数据错误，清空缓冲区
                        buffer = buffer[end+1:]
                
            except socket.timeout:
                print("接收超时,未收到服务器响应")
                break
                
    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        print("关闭连接")
        sock.close()

def main():
    parser = argparse.ArgumentParser(description='TCP客户端')
    parser.add_argument('--host', type=str, default='localhost',
                      help='服务器地址 (默认: localhost)')
    parser.add_argument('--port', type=int, default=15006,
                      help='服务器端口 (默认: 15006)')
    
    # 使用更紧凑的JSON格式
    # data = {
    #     "action": "orderInsert",
    #     "data": {
    #         "instrument": "rb2505",
    #         "exchange": "SHFE",
    #         "direction": "buy",
    #         "price": 3300.00,
    #         "volume": 1,
    #         "offect": "open"
    #     }
    # }
    # data = {
    #     "action": "subscribe",
    #     "data": {
    #         "instrument": "rb2505"
    #     }
    # }
    # data = {
    #     "action": "getPosition",
    #     "data": {
    #     }
    # }
    # data = {
    #     "action": "getAccount",
    #     "data": {
    #     }   
    # }
    # data = {
    #     "action": "getTrade",
    #     "data": {
    #     }
    # }
    # data = {    
    #     "action": "getOrder",
    #     "data": {
    #         "exchange": "SHFE"
    #     }
    # }
    data = {
        "action": "orderCancel",
        "data": {
            "instrument": "rb2505",
            "exchange": "SHFE",
            "sid": "       78735"
        }
    }
    parser.add_argument('--message', type=str, default=json.dumps(data),
                      help='要发送的消息 (JSON格式)')
    
    args = parser.parse_args()
    
    print("启动TCP客户端...")
    print(f"目标服务器: {args.host}:{args.port}")
    
    send_message(args.host, args.port, args.message)

if __name__ == "__main__":
    main() 